<template>
  <div>
    <h1 class="page-title">系统总览</h1>
    
    <!-- Stats Cards -->
    <div class="card-container">
      <a-card title="药品总数" :bordered="false">
        <template #extra>
          <medicine-box-outlined style="color: #1890ff" />
        </template>
        <a-statistic :value="stats.total_medicines || 0" :precision="0">
          <template #suffix>
            <span>个</span>
          </template>
        </a-statistic>
      </a-card>
      
      <a-card title="追溯事件总数" :bordered="false">
        <template #extra>
          <apartment-outlined style="color: #52c41a" />
        </template>
        <a-statistic :value="stats.total_events || 0" :precision="0">
          <template #suffix>
            <span>次</span>
          </template>
        </a-statistic>
      </a-card>
      
      <a-card title="今日验证次数" :bordered="false">
        <template #extra>
          <safety-certificate-outlined style="color: #faad14" />
        </template>
        <a-statistic :value="todayVerifications" :precision="0">
          <template #suffix>
            <span>次</span>
          </template>
        </a-statistic>
      </a-card>
      
      <a-card title="系统运行状态" :bordered="false">
        <template #extra>
          <cluster-outlined style="color: #13c2c2" />
        </template>
        <a-badge status="processing" text="运行正常" />
        <div>
          <a-tag color="green">API正常</a-tag>
          <a-tag color="green">RFID扫描器连接正常</a-tag>
          <a-tag color="green">数据库正常</a-tag>
        </div>
      </a-card>
    </div>
    
    <!-- Recent Events -->
    <a-card title="最近事件" class="mt-16">
      <a-table
        :dataSource="recentEvents"
        :columns="columns"
        :pagination="{ pageSize: 5 }"
        size="middle"
        :loading="loading"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'event_type'">
            <a-tag :color="getEventTypeColor(record.event_type)">
              {{ getEventTypeText(record.event_type) }}
            </a-tag>
          </template>
          <template v-if="column.key === 'action'">
            <a-button type="link" size="small" @click="viewDetail(record)">
              查看详情
            </a-button>
          </template>
        </template>
      </a-table>
    </a-card>
    
    <!-- Event Type Distribution Chart -->
    <a-card title="事件类型分布" class="mt-16">
      <div ref="chartRef" style="height: 300px"></div>
    </a-card>
    
    <!-- Event Detail Modal -->
    <a-modal v-model:visible="visible" title="事件详情" @ok="handleOk">
      <a-descriptions bordered>
        <a-descriptions-item label="RFID ID" span="3">
          {{ currentEvent?.rfid_id }}
        </a-descriptions-item>
        <a-descriptions-item label="事件类型" span="3">
          <a-tag :color="getEventTypeColor(currentEvent?.event_type)">
            {{ getEventTypeText(currentEvent?.event_type) }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="地点" span="3">
          {{ currentEvent?.location }}
        </a-descriptions-item>
        <a-descriptions-item label="操作人员" span="3">
          {{ currentEvent?.operator }}
        </a-descriptions-item>
        <a-descriptions-item label="备注" span="3">
          {{ currentEvent?.notes }}
        </a-descriptions-item>
        <a-descriptions-item label="时间" span="3">
          {{ formatDate(currentEvent?.timestamp) }}
        </a-descriptions-item>
      </a-descriptions>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import * as echarts from 'echarts'
import moment from 'moment'
import api from '@/services/api'
import {
  MedicineBoxOutlined,
  ApartmentOutlined,
  SafetyCertificateOutlined,
  ClusterOutlined
} from '@ant-design/icons-vue'

interface SystemStats {
  total_medicines: number
  total_events: number
  recent_events: any[]
  event_types: Record<string, number>
}

interface EventRecord {
  rfid_id: string
  event_type: string
  location: string
  operator: string
  notes: string
  timestamp: string
}

const stats = reactive<SystemStats>({
  total_medicines: 0,
  total_events: 0,
  recent_events: [],
  event_types: {}
})

const chartRef = ref<HTMLElement | null>(null)
const loading = ref(true)
const visible = ref(false)
const currentEvent = ref<EventRecord | null>(null)

const columns = [
  {
    title: 'RFID ID',
    dataIndex: 'rfid_id',
    key: 'rfid_id',
    width: 170
  },
  {
    title: '事件类型',
    dataIndex: 'event_type',
    key: 'event_type',
    width: 120
  },
  {
    title: '地点',
    dataIndex: 'location',
    key: 'location'
  },
  {
    title: '操作人员',
    dataIndex: 'operator',
    key: 'operator'
  },
  {
    title: '时间',
    dataIndex: 'timestamp',
    key: 'timestamp',
    render: (text: string) => formatDate(text)
  },
  {
    title: '操作',
    key: 'action',
    width: 100
  }
]

const todayVerifications = computed(() => {
  // Count verifications today
  return stats.recent_events.filter(event => 
    event.event_type === 'verification' && 
    moment(event.timestamp).isSame(moment(), 'day')
  ).length
})

const recentEvents = computed(() => {
  return stats.recent_events.map((event, index) => ({
    ...event,
    key: index
  }))
})

function getEventTypeColor(type: string | undefined): string {
  const colors: Record<string, string> = {
    'production': 'blue',
    'storage': 'cyan',
    'transport': 'purple',
    'sale': 'green',
    'verification': 'orange',
    'scan': 'geekblue'
  }
  return colors[type || ''] || 'default'
}

function getEventTypeText(type: string | undefined): string {
  const texts: Record<string, string> = {
    'production': '生产',
    'storage': '入库',
    'transport': '运输',
    'sale': '销售',
    'verification': '验证',
    'scan': '扫描'
  }
  return texts[type || ''] || type || ''
}

function formatDate(date: string | undefined): string {
  if (!date) return ''
  return moment(date).format('YYYY-MM-DD HH:mm:ss')
}

function viewDetail(record: EventRecord) {
  currentEvent.value = record
  visible.value = true
}

function handleOk() {
  visible.value = false
}

function renderChart() {
  if (!chartRef.value) return
  
  const myChart = echarts.init(chartRef.value)
  const eventTypes = stats.event_types || {}
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 10,
      data: Object.keys(eventTypes).map(type => getEventTypeText(type))
    },
    series: [
      {
        name: '事件类型',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 40,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: Object.entries(eventTypes).map(([type, count]) => ({
          value: count,
          name: getEventTypeText(type)
        }))
      }
    ]
  }
  
  myChart.setOption(option)
  
  window.addEventListener('resize', () => {
    myChart.resize()
  })
}

async function fetchData() {
  loading.value = true
  try {
    const response = await api.getSystemStats()
    stats.total_medicines = response.data.total_medicines
    stats.total_events = response.data.total_events
    stats.recent_events = response.data.recent_events
    stats.event_types = response.data.event_types
    
    // Render chart after data is loaded
    renderChart()
  } catch (error) {
    console.error('Failed to fetch system stats:', error)
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchData()
  
  // Auto refresh data every 30 seconds
  const intervalId = setInterval(fetchData, 30000)
  
  // Clean up interval on component unmount
  return () => {
    clearInterval(intervalId)
  }
})
</script>

<style scoped>
.page-title {
  margin-bottom: 24px;
}
</style> 